package com.registration;


import org.apache.curator.framework.recipes.cache.CuratorCache;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public class CacheMap<K,V> extends LinkedHashMap<K,V> {


    private volatile int maxSize = 0;

    private CacheMap map;

    public synchronized void setMaxSize(int maxSize){
        this.maxSize = maxSize;
    }

    public CacheMap(int maxSize){
        super((int)Math.ceil(maxSize/0.75f)+1,0.75f,true);
        this.maxSize = maxSize;
    }

    @Override
    public boolean removeEldestEntry(
            Map.Entry<K, V> eldest) {
        boolean needRemove = size()>maxSize;
        if(needRemove) {
            CuratorCache cache = (CuratorCache)eldest.getValue();
            cache.close();
        }
        return needRemove;
    }

    @Override
    public synchronized V get(Object key){
        if(key==null) return null;
        return super.get(key);
    }

    @Override
    public synchronized V remove(Object key) {
        CuratorCache cache = (CuratorCache) super.remove(key);
        cache.close();
        return (V)cache;
    }

    @Override
    public V putIfAbsent(K key, V value) {
        return super.putIfAbsent(key, value);
    }

    @Override
    public synchronized V put(K key, V val){
        return super.put(key,val);
    }

    @Override
    public synchronized boolean containsKey(Object key){
        return super.containsKey(key);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;
        CacheMap<?, ?> cacheMap = (CacheMap<?, ?>) o;
        return maxSize == cacheMap.maxSize && Objects.equals(map, cacheMap.map);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), maxSize, map);
    }
}
